package com.sdy.mvc.utils;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sdy.common.model.FileObj;
import com.sdy.common.model.PageResult;
import com.sdy.common.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 使用Jackson序列化
 * 序列化过程参照 Spring Data Redis 中的序列化
 * {@link org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer}
 * Created by zzq on 2017-08-23.
 */
@Slf4j
public class JsonUtil {

    private static final GenericJackson2JsonRedisSerializer genericSerializer = new GenericJackson2JsonRedisSerializer();
    private static final ObjectMapper jsonSerializerMapper = new ObjectMapper();
    
    static {
        /**
         * 反序列化时忽略不存在的字段
         */
        jsonSerializerMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    /**
     * 对象转json
     *
     * @param object
     * @return
     */
    public static String toJson(Object object) {
        try {
            return jsonSerializerMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            log.error("", e);
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * json转对象
     *
     * @param json
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T fromJson(String json, Class<T> clazz) {
        try {
            return jsonSerializerMapper.readValue(json, clazz);
        } catch (IOException e) {
            log.error("", e);
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 序列化
     *
     * @param object
     * @return
     */
    public static byte[] serialize(Object object) {
        return genericSerializer.serialize(object);
    }

    /**
     * 反序列化
     *
     * @param source
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T deserialize(byte[] source, Class<T> clazz) {
        return genericSerializer.deserialize(source, clazz);
    }

    /**
     * POJO类型转换
     */
    public static <T, K> T convert(K k, Class<T> clazz) {
        return JsonUtil.fromJson(JsonUtil.toJson(k), clazz);
    }

    /**
     * POJO类型转换(Page分页泛型)
     */
    public static <T, K> IPage<T> convertPage(IPage<K> k, Class<T> clazz) {
        if (k.getRecords() == null) {
            throw new RuntimeException("未找到记录");
        }
        List<T> list = k.getRecords().stream().map(item -> convert(item, clazz)).collect(Collectors.toList());
        return new Page<T>(k.getCurrent(), k.getSize(), k.getTotal()).setRecords(list);
    }

    /**
     * POJO类型转换(Page分页泛型)
     */
    public static <T, K> PageResult<T> convertPage2(PageResult<K> k, Class<T> clazz) {
        if (k.getRecords() == null) {
            throw new RuntimeException("未找到记录");
        }
        List<T> list = k.getRecords().stream().map(item -> convert(item, clazz)).collect(Collectors.toList());
        return new PageResult<>(k.getCurrent(), k.getSize(), k.getTotal(), list);
    }

    /**
     * POJO类型转换(List集合泛型)
     */
    @SuppressWarnings("unchecked")
    public static <T, K, R> T convertCollection(K k, Class<T> clazz, Class<R> clz) {
        boolean s2 = Collection.class.isAssignableFrom(clazz);
        if (List.class.isAssignableFrom(clazz) && List.class.isAssignableFrom(k.getClass())) {
            return (T)((List) k).stream()
                    .map(item -> convert(item, clz))
                    .collect(Collectors.toList());
        } else if (Set.class.isAssignableFrom(clazz) && Set.class.isAssignableFrom(k.getClass())) {
            return (T)((Set) k).stream()
                    .map(item -> convert(item, clz))
                    .collect(Collectors.toSet());
        }
        return convert(k, clazz);
    }

    @SuppressWarnings("unchecked")
    public static List<FileObj> convertJsonToFileObjs(String json) {
        if (StringUtil.isBlank(json)) {
            json = "[]";
        }
        List<Map> objs = JsonUtil.fromJson(json, List.class);
        List<FileObj> fileObjList = new ArrayList<>();
        objs.forEach(obj -> {
            fileObjList.add(new FileObj()
                    .setPath((String) obj.get("path"))
                    .setId((String) obj.get("id"))
                    .setFileName((String) obj.get("fileName")));
        });
        return fileObjList;
    }

    public static String convertFileObjsToJson(List<FileObj> fileObjList) {
        if (fileObjList == null) {
            fileObjList = Collections.emptyList();
        }
        return JsonUtil.toJson(fileObjList);
    }
}
